//
//  ViewController.m
//  ivcs_ios_demo
//
//  Created by zealcomm user on 2020/10/21.
//  Copyright © 2020 zealcomm user. All rights reserved.
//

#import "ViewController.h"
#import <objc/runtime.h>
@interface ViewController ()<CCSClientDelegate,UIDocumentPickerDelegate>
@property(nonatomic,strong)IVCSSDK *ivcsSdk;
@property(nonatomic,copy)NSString *sessionId;
@property(nonatomic,strong)NSDictionary *user;
@property (strong, nonatomic) UIActivityIndicatorView *activityIndicator ;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}


- (IBAction)init:(id)sender {
    self.ivcsSdk = [IVCSSDK shareSDK];
    NSString *url = @"https://ivcs-demo.zealcomm.cn";
    NSString *name = self.name.text;
    NSString *pwd = self.password.text;
    NSString *org = self.org.text;
    
    [self.ivcsSdk initWithServiceUrl:url name:name password:pwd org:org mediaOptions:nil onSuccess:^(NSDictionary * _Nonnull result) {
        NSLog(@"init success,,%@",result);
        NSDictionary *user = [self jwtDecodeWithJwtString:[[result valueForKey:@"data"] valueForKey:@"accessToken"]];
        NSLog(@"%@",user);
        self.user = [NSDictionary dictionaryWithDictionary:user];
        [self showAlert:@"初始化成功，可发起呼叫" onOK:^{
            
        } onCancel:^{
            
        }];
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"init error,,%@",error);
        [self showAlert:@"初始化失败" onOK:^{
            
        } onCancel:^{
            
        }];
    }];
}


- (IBAction)requestSession:(id)sender {
    NSDictionary *option = @{
        @"media":@"video",
        @"userData":@{
                @"service":self.serviceId.text,
                @"specifyAgent":@"",
                },
        @"clientInfo":@"ios"
    };
    self.ivcsSdk.ccsClient.delegate = self;
    [self.ivcsSdk requestSession:option onSuccess:^(NSDictionary * _Nonnull result) {
        NSLog(@"request session success,,%@",result);
         self.sessionId = [result valueForKey:@"sessionId"];
        [self startActivityIndicator];
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"error,%@",error);
        [self showAlert:@"呼叫失败" onOK:^{
            
        } onCancel:^{
            
        }];
    }];
}

#pragma mark CCSClientDelegate
-(void)requestSessionProgress:(NSDictionary *)progress{
    NSLog(@"parogress,,%@",progress);
    if ([[[progress valueForKey:@"data"] valueForKey:@"status"] isEqualToString:@"notfound"]) {
        NSLog(@"暂无可用坐席");
     }
    else if ([[[progress valueForKey:@"data"] valueForKey:@"status"] isEqualToString:@"waiting"]) {
                  NSLog(@"正在等待坐席接听");
               }
   else if ([[[progress valueForKey:@"data"] valueForKey:@"status"] isEqualToString:@"connecting"]) {
                   NSLog(@"坐席正在建立连接");
   }else if([[[progress valueForKey:@"data"] valueForKey:@"status"] isEqualToString:@"accepted"]){
                   NSLog(@"坐席已接听，正在准备视频");
       //判断是否是机器人坐席
       if ([[progress valueForKey:@"data"] valueForKey:@"agent"]) {
           if ([[[progress valueForKey:@"data"] valueForKey:@"agent"] valueForKey:@"user"]) {
                     if ([[[[progress valueForKey:@"data"] valueForKey:@"agent"] valueForKey:@"user"] valueForKey:@"profile"]) {
                         if ([[[[[[progress valueForKey:@"data"] valueForKey:@"agent"] valueForKey:@"user"] valueForKey:@"profile"] valueForKey:@"isRobot"] isEqualToNumber:[NSNumber numberWithInt:1]]) {
                             NSLog(@"is robot agent");
                             [self isRobotAgent];
                         }
                     }
          }
       }
    }
}

-(void)isRobotAgent{
    [self hideActivityIndicator];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SessionViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"sessionVc"];
    vc.ivcsSdk = self.ivcsSdk;
    vc.sessionId = self.sessionId;
    vc.isRobotAgent = true;
    vc.user = self.user;
    [self.navigationController pushViewController:vc animated:true];
}

-(void)agentVideoReadyToTalk{
    [self hideActivityIndicator];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SessionViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"sessionVc"];
    vc.ivcsSdk = self.ivcsSdk;
    vc.sessionId = self.sessionId;
    vc.isRobotAgent = false;
    vc.user = self.user;
    [self.navigationController pushViewController:vc animated:true];
}




- (IBAction)cancelRequest:(id)sender {
    [self.ivcsSdk quitSession:nil onSuccess:^{
        NSLog(@"quit Success");
        [self showAlert:@"取消呼叫成功" onOK:^{
            
        } onCancel:^{
            
        }];
    } onFailure:^(NSError * _Nonnull error) {
        NSLog(@"...%@",error);
        [self showAlert:@"取消呼叫失败" onOK:^{
            
        } onCancel:^{
            
        }];
    }];
}

-(id)jwtDecodeWithJwtString:(NSString *)jwtStr {
    NSArray * segments = [jwtStr componentsSeparatedByString:@"."];
    NSString * base64String = [segments objectAtIndex:1];
    int requiredLength = (int)(4 *ceil((float)[base64String length]/4.0));
    int nbrPaddings = requiredLength - (int)[base64String length];
    if(nbrPaddings > 0){
        NSString * pading = [[NSString string] stringByPaddingToLength:nbrPaddings withString:@"=" startingAtIndex:0];
        base64String = [base64String stringByAppendingString:pading];
    }
    base64String = [base64String stringByReplacingOccurrencesOfString:@"-" withString:@"+"];
    base64String = [base64String stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
    NSData * decodeData = [[NSData alloc] initWithBase64EncodedData:base64String options:0];
    NSString * decodeString = [[NSString alloc] initWithData:decodeData encoding:NSUTF8StringEncoding];
    NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:[decodeString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    return jsonDict;
}

- (void)showAlert:(NSString *)message onOK:(void(^)(void))ok onCancel:(void(^)(void))cancel{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
        ok();
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
        cancel();
                                                          }];

    [alert addAction:cancelAction];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)startActivityIndicator{
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake((self.view.frame.size.width-100)/2, 200, 100, 100)];
    [self.view addSubview:self.activityIndicator];
    self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.activityIndicator startAnimating];
}

-(void)hideActivityIndicator{
    [self.activityIndicator stopAnimating];
}


@end
